﻿// Copyright (c) Inossem. All rights reserved.
// Licensed under the LGPL-3.0 license. See LICENSE file in the project root for full license information.
using DWF.Studio.Custom;
using DWF.Studio.ISerivces;
using DWF.Studio.Models;
using DWF.Studio.NuGetManagement;
using DWF.Studio.Services;
using Ookii.Dialogs.Wpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using WpfMessageBoxLibrary;

namespace DWF.Studio.Views
{
    /// <summary>
    /// UCtrlPackageSourceManagement.xaml 的交互逻辑
    /// </summary>
    public partial class UCtrlPackageSourceManagement : UserControl
    {
        /// <summary>
        /// 
        /// </summary>
        private IConfigService _configService = null;
        /// <summary>
        /// 自定义包源
        /// </summary>
        private ObservableCollection<PackageSourceUri> _customPackageSourceUri = new ObservableCollection<PackageSourceUri>();
        /// <summary>
        /// 默认包源
        /// </summary>
        private ObservableCollection<PackageSourceUri> _defaultPackageSourceUri = new ObservableCollection<PackageSourceUri>();

        public UCtrlPackageSourceManagement()
        {
            InitializeComponent();
            if (!DesignerProperties.GetIsInDesignMode(this))
            {
                init();
            }
        }
        /// <summary>
        /// 初始化
        /// </summary>
        private void init()
        {
            _configService = new ConfigService();
            getDefaultPackageSource();
            this.defaultPackageSource.ItemsSource = _defaultPackageSourceUri;
            this.customPackageSource.ItemsSource = _customPackageSourceUri;
        }
        /// <summary>
        /// 获取默认包
        /// </summary>
        private void getDefaultPackageSource()
        {
            _defaultPackageSourceUri.Clear();
            _customPackageSourceUri.Clear();
            var config = _configService.LoadSysConfig();
            config.PackageUris.Where(o => o.IsDefault == true).ToList().ForEach(p => _defaultPackageSourceUri.Add(p));
            config.PackageUris.Where(o => o.IsDefault == false).ToList().ForEach(p => _customPackageSourceUri.Add(p));
        }
        /// <summary>
        /// 自定义包点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void customPackageSource_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count>0)
            {
                this.addPackage.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageDetail_Button_Content_Update");
                var _packageSourceUri = e.AddedItems[0] as PackageSourceUri;
                this.packageSourceName.Text = _packageSourceUri.DisplayName;
                this.packageAddress.Text = _packageSourceUri.PackageUrl;
                this.deletePackage.IsEnabled = true;
            }
        }
        #region 失去焦点取消文本框内容 修改按钮文字
        /// <summary>
        /// 鼠标点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void customPackageSource_MouseDown(object sender, MouseButtonEventArgs e)
        {
            clearPackageSource();
        }
        private void defaultPackageSource_MouseDown(object sender, MouseButtonEventArgs e)
        {
            clearPackageSource();
        }
        private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
        {
            clearPackageSource();
        }
        private void clearPackageSource()
        {
            this.addPackage.Content = LocalizationProvider.GetLocalizedString("UCtrlPackageSourceManagement_Btn_Add");
            this.packageSourceName.Text = null;
            this.packageAddress.Text = null;
            this.customPackageSource.SelectedItem = null;
            this.deletePackage.IsEnabled = false;
        }
        #endregion
        /// <summary>
        /// 删除自定义包源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void deletePackage_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(this.packageSourceName.Text) || string.IsNullOrEmpty(this.packageAddress.Text))
                return;
            var config = _configService.LoadSysConfig();
            var configpackageuri = config.PackageUris.Where(o => o.Name == this.packageSourceName.Text && o.DisplayName == this.packageSourceName.Text && o.PackageUrl == this.packageAddress.Text && o.IsDefault == false).FirstOrDefault();
            config.PackageUris.Remove(configpackageuri);
            var custompackageuri = _customPackageSourceUri.Where(o => o.Name == this.packageSourceName.Text && o.DisplayName == this.packageSourceName.Text && o.PackageUrl == this.packageAddress.Text && o.IsDefault == false).FirstOrDefault();
            _customPackageSourceUri.Remove(custompackageuri);
            _configService.SaveSysConfig(config);
            clearPackageSource();
        }
        /// <summary>
        /// 添加自定义包源
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void addPackage_Click(object sender, RoutedEventArgs e)
        {
            Color color = (Color)ColorConverter.ConvertFromString("#EA5050");
            SolidColorBrush brush = new SolidColorBrush(color);
            var config = _configService.LoadSysConfig();
            if (string.IsNullOrWhiteSpace(this.packageSourceName.Text))
            {
                var msgProperties = new WpfMessageBoxProperties()
                {
                    Button = MessageBoxButton.OK,
                    ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Ok"),
                    Image = MessageBoxImage.Warning,
                    Text = string.Format(LocalizationProvider.GetLocalizedString("UCtrlPackageSourceManagement_Msg_SourceName_Error")),
                    Title = LocalizationProvider.GetLocalizedString("WindowCreateProject_MsgBox_Caption_Create_NameValidate"),
                };
                Window owner = Window.GetWindow(this);
                WpfMessageBox.Show(owner, ref msgProperties);

                Keyboard.Focus(packageSourceName);
                packageSourceName.BorderBrush = brush;
                return;
            }
            if (string.IsNullOrWhiteSpace(this.packageAddress.Text))
            {
                var msgProperties = new WpfMessageBoxProperties()
                {
                    Button = MessageBoxButton.OK,
                    ButtonOkText = LocalizationProvider.GetLocalizedString("MessageBox_Button_Ok"),
                    Image = MessageBoxImage.Warning,
                    Text = string.Format(LocalizationProvider.GetLocalizedString("UCtrlPackageSourceManagement_Msg_Address_Error")),
                    Title = LocalizationProvider.GetLocalizedString("WindowCreateProject_MsgBox_Caption_Create_NameValidate"),
                };
                Window owner = Window.GetWindow(this);
                WpfMessageBox.Show(owner, ref msgProperties);

                Keyboard.Focus(packageAddress);
                packageAddress.BorderBrush = brush;
                return;
            }
            var packageuri = new PackageSourceUri(this.packageSourceName.Text, this.packageSourceName.Text, this.packageAddress.Text);
            if (config.PackageUris.Where(o => o.DisplayName == packageuri.DisplayName && o.PackageUrl == packageuri.PackageUrl).FirstOrDefault() != null)
            {
                clearPackageSource();
                return;
            }
            if (this.customPackageSource.SelectedItem == null) //添加
            {
                config.PackageUris.Add(packageuri);
                _customPackageSourceUri.Add(packageuri);
                _configService.SaveSysConfig(config);
            }
            else
            {
                var removePackageSource = this.customPackageSource.SelectedItem as PackageSourceUri;
                var configpackageuri = config.PackageUris.Where(o => o.Name == removePackageSource.Name && o.DisplayName == removePackageSource.DisplayName && o.PackageUrl == removePackageSource.PackageUrl && o.IsDefault == false).FirstOrDefault();
                config.PackageUris.Remove(configpackageuri);
                var custompackageuri = _customPackageSourceUri.Where(o => o.Name == removePackageSource.Name && o.DisplayName == removePackageSource.DisplayName && o.PackageUrl == removePackageSource.PackageUrl && o.IsDefault == false).FirstOrDefault();
                _customPackageSourceUri.Remove(custompackageuri);

                config.PackageUris.Add(packageuri);
                _customPackageSourceUri.Add(packageuri);
                _configService.SaveSysConfig(config);
            }
            
            clearPackageSource();
        }
        /// <summary>
        /// 默认包是否使用事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            var item = ((ListBoxItem)defaultPackageSource.ContainerFromElement((System.Windows.Controls.CheckBox)sender)).Content as PackageSourceUri;
            var config = _configService.LoadSysConfig();
            if ((sender as CheckBox).IsChecked == true)
            {
                config.PackageUris.Where(o => o.DisplayName == item.DisplayName && o.PackageUrl == item.PackageUrl && o.IsDefault == true).FirstOrDefault().Apply = true;
            }
            else
            {
                config.PackageUris.Where(o => o.DisplayName == item.DisplayName && o.PackageUrl == item.PackageUrl && o.IsDefault == true).FirstOrDefault().Apply = false;
            }
            _configService.SaveSysConfig(config);
        }
        /// <summary>
        /// 自定义包是否使用事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CheckBox_Click_1(object sender, RoutedEventArgs e)
        {
            var item = ((ListBoxItem)customPackageSource.ContainerFromElement((System.Windows.Controls.CheckBox)sender)).Content as PackageSourceUri;
            var config = _configService.LoadSysConfig();
            
            if ((sender as CheckBox).IsChecked == true)
            {
                config.PackageUris.Where(o=>o.IsDefault==false).ToList().ForEach(o => o.Apply = false);
                config.PackageUris.Where(o => o.DisplayName == item.DisplayName && o.PackageUrl == item.PackageUrl).FirstOrDefault().Apply = true;
            }
            else
            {
                config.PackageUris.Where(o => o.DisplayName == item.DisplayName && o.PackageUrl == item.PackageUrl).FirstOrDefault().Apply = false;
            }
            _customPackageSourceUri.Clear();
            config.PackageUris.Where(o => o.IsDefault == false).ToList().ForEach(p => _customPackageSourceUri.Add(p));
            _configService.SaveSysConfig(config);
            clearPackageSource();
        }

        private void packageSourceName_TextChanged(object sender, TextChangedEventArgs e)
        {
            Color color = (Color)ColorConverter.ConvertFromString("#BCBCBC");
            SolidColorBrush brush = new SolidColorBrush(color);
            packageSourceName.BorderBrush = brush;
            return;
        }

        private void packageAddress_TextChanged(object sender, TextChangedEventArgs e)
        {
            Color color = (Color)ColorConverter.ConvertFromString("#BCBCBC");
            SolidColorBrush brush = new SolidColorBrush(color);
            packageAddress.BorderBrush = brush;
            return;
        }

        private void btnDirectory_Click(object sender, RoutedEventArgs e)
        {
            VistaFolderBrowserDialog projectDialog = new VistaFolderBrowserDialog();
            var result = projectDialog.ShowDialog(App.Current.MainWindow);

            if (result == true)
            {
                this.packageAddress.Text = projectDialog.SelectedPath;
            }
        }
    }
}
